import Vue from "vue";
import jspdfHtml2PDF from 'jspdf-html2canvas'
import JsZip from 'jszip'
import FileSaver from 'file-saver'

// 导出html2PDF
export const exportPDF = async (doms, filename, loadBool = true) => {
  if (loadBool) await Vue.prototype.$loading({ text: '努力导出中' })
  jspdfHtml2PDF(doms, {
    jsPDF: {
      format: 'a4'
    },
    imageType: 'image/jpeg',
    init: function() {},
    success: function(pdf) {
      pdf.save(`${filename}.pdf`)
      if (loadBool) Vue.prototype.$loading().close()
    }
  })
}

export const successPDF = async (doms, filename, loadBool = true) => {
  // if(loadBool) await Vue.prototype.$loading({ text: '努力导出中' })
  return new Promise((reslove, reject) => {
    const zip = new JsZip()
    jspdfHtml2PDF(doms, {
      jsPDF: {
        format: 'a4'
      },
      imageQuality: 1,
      imageType: 'image/jpeg',
      output: 'jspdf-generate.pdf',
      init: function() {},
      success: function(pdf) {
        // reslove(pdf)
        // var pdfData = pdf.output( 'blob' ) //获取base64Pdf
        var pdfData = pdf.output('datauristring') //获取base64Pdf
        // 转base64
        // const datauri = pdf.output('dataurlstring')
        // const base64 = pdfData.substring(44)
        // var base = window.atob(pdfData)  //解码
        // console.log(pdfData)
        // pdfData.replace(/^data:application\/(pdf);filename=generated.pdf;base64,/, "")
        // zip.file('smile.pdf', pdfData, { base64: true })
        // // img.file('sww.jpg', this.imgurl.split('base64,')[1], { base64: true })
        // zip.generateAsync({ type: 'blob' }).then(function(content) {
        //   FileSaver.saveAs(content, `${filename}.zip`)
        // })
        reslove(pdfData)
        // pdf.save(`${filename}.pdf`)
        // if(loadBool) Loading().close()
      }
    })
  })
}

// 把pdf文件压缩到zip
export const exportZip = filename => {
  const zip = new JsZip()
  // const pdf = zip.folder('pdf')
  // var img = zip.folder('images')
  // const splitbase64 = this.base64pdf.split('base64,')[1]
  var imgData = 'R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs='
  zip.file('2Hello.txt', 'Hello World\n')
  zip.file('test.txt', 'He99999d\n')
  // pdf.file(`${filename}.pdf`, splitbase64, { base64: true })
  zip.file('smile.gif', imgData, { base64: true })
  // img.file('sww.jpg', this.imgurl.split('base64,')[1], { base64: true })
  zip.generateAsync({ type: 'blob' }).then(function(content) {
    FileSaver.saveAs(content, `${filename}.zip`)
  })
}

export default {
  exportPDF,
  successPDF,
  exportZip
}
